package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.nft.dao.OpenPageDao;
import com.sc.nft.entity.OpenPage;
import com.sc.nft.entity.vo.AdminOpenPageVO;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.OpenPageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@RequiredArgsConstructor
@Service
public class OpenPageServiceImpl implements OpenPageService {
    private final OpenPageDao openPageDao;

    @Override
    public Page<AdminOpenPageVO> pageAdmin(String firstTitle, int pageNo, int pageSize) {
        return openPageDao.pageAdmin(firstTitle, pageNo, pageSize);
    }

    @Override
    public OpenPage getOne() {
        OpenPage one = openPageDao.getOpenOne();
        if (BeanUtil.isEmpty(one)) {
            return null;
        }
        return one;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(String firstTitle, String image) {
        OpenPage openPage = new OpenPage();
        openPage.setIsOpen(Boolean.FALSE);
        openPage.setFirstTitle(firstTitle);
        openPage.setImage(image);
        boolean flag = openPage.insert();
        if (!flag) {
            throw new GlobalRunTimeException("开屏页新增失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        OpenPage openPage = openPageDao.getById(id);
        if (openPage.getIsOpen()) {
            throw new GlobalRunTimeException("上架中的开屏页无法删除");
        }
        if (!openPageDao.deleteById(id)) {
            throw new GlobalRunTimeException("删除失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(Long id, String firstTitle, String image) {
        OpenPage openPage = openPageDao.getById(id);
        if (ObjectUtil.isNull(openPage)) {
            throw new GlobalRunTimeException("不存在此开屏页");
        }
        if(!openPageDao.updateById(id, firstTitle, image)){
            throw new GlobalRunTimeException("修改失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateIsOpenById(Long id, Boolean isOpen) {
        OpenPage openPage = openPageDao.getById(id);
        if (ObjectUtil.isNull(openPage)) {
            throw new GlobalRunTimeException("不存在此开屏页");
        }
        //上架时 有已经上架的开屏页的话自动下架其他开屏页
        if (isOpen) {
           openPageDao.closeOpenPage();
        }
        OpenPage update = new OpenPage();
        update.setId(id);
        update.setIsOpen(isOpen);
        if (!update.updateById()) {
            throw new GlobalRunTimeException("配置失败");
        }
    }
}
